﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Web.Services;
using BasicMachine.SecurityService;
using BasicMachine.MessageServerice;

namespace BasicMachine
{
    public class SMS
    {
       
        private Security oSecurity;
        private Message oMessage;
        private string m_sCustID = "av8d20";
        private double m_iCredit = 0;
        private string m_sCompanyNo="";
        private string m_sUserNo ="";

        /// <summary>
        /// Constructor for SMS
        /// </summary>

        public SMS(){

            oSecurity = new SecurityService.Security();
            oMessage = new MessageServerice.Message();
             

        }

        public bool Login(string UserID, string Password)
        {
            try
            {
                bool bLogin = false;
                // 執行Login
                string ResultXml = oSecurity.Login(m_sCustID, UserID, Password, "", "");

                //分析回傳xml
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(ResultXml);
                string ErrorCode = doc.SelectSingleNode("/USER/ERROR_CODE").InnerText;
                if (ErrorCode == "0000")  //登入成功
                {
                    bLogin = true;
                    m_sCompanyNo = doc.SelectSingleNode("/USER/COMPANY_NO").InnerText;  //所屬公司代碼,簡訊發送時需傳入
                    m_sUserNo = doc.SelectSingleNode("/USER/USER_NO").InnerText;        //所屬使用者代碼,簡訊發送時需傳入
                    m_iCredit = Convert.ToDouble(doc.SelectSingleNode("/USER/CREDIT").InnerText); //目前點數餘額

                }

                return bLogin;
            }
            catch
            {
                return false;
            }

        }

        /// <summary>
        /// 傳送一般簡訊，超過字數時將自動拆則
        /// </summary>
        /// <remarks>傳送一般簡訊，超過字數時(140byes;中文70字;英文140字)將自動拆則</remarks>
        /// <param name="Subject">傳送之主旨，主旨內容不會隨簡訊發送出去，用於報表中查詢，方便管理之用</param>
        /// <param name="Content">傳送簡訊之內容</param>
        /// <param name="SendTime">預計傳送時間，帶入空字串時，則立即傳送；若需預約傳送時，帶入格式為yyyyMMddhhmnss，例如:2009/01/01 13:00:00 則傳入20090101130000</param>
        /// <param name="PhoneNumbers">要傳送之電話號碼，多筆時以逗點(,)隔開。若為國際電話時，請用+86xxxxxxxx格式</param>
        /// <returns>true:傳送成功；false:傳送失敗</returns>
        public Boolean sendMessage( string Subject, string Content, string SendTime,string PhoneNumbers)
        {
            try
            {


                if(SendTime != ""){
                    if(SendTime.Length != 14){  //檢查傳送時間是否長度正確
                        return false;
                    }
                }

                Content += "; rs.期貨工作室";
                string sendingXML =getSendingXML(PhoneNumbers,SendTime);
                string sResult="";
                TimeSpan STARTTIME = new TimeSpan(8, 30, 0);
                TimeSpan ENDTIME = new TimeSpan(13, 46, 0);

                if ((DateTime.Now.Date.DayOfWeek != DayOfWeek.Saturday) && (DateTime.Now.TimeOfDay < ENDTIME) && (DateTime.Now.TimeOfDay > STARTTIME))
                    sResult = oMessage.QueueIn(m_sCustID, m_sCompanyNo, m_sUserNo, "100", "10", Subject, Content, "", "", sendingXML, "", "");
               
                
                if(sResult.Substring(0,1)=="-"){ // 發送失敗
                    return false;
                }

                string[] split = sResult.Split(',');
                m_iCredit = Convert.ToInt32(split[0]);

                return true;


            }
            catch
            {
                return false;
            }
        }
         /// <summary>
        /// 傳送長簡訊，335(中文)字內有效，超過則自動進行拆則
        /// </summary>
        /// <remarks>傳送長簡訊，335(中文)字內有效，超過則自動進行拆則</remarks>
        /// <param name="Subject">傳送之主旨，主旨內容不會隨簡訊發送出去，用於報表中查詢，方便管理之用</param>
        /// <param name="Content">傳送簡訊之內容</param>
        /// <param name="SendTime">預計傳送時間，帶入空字串時，則立即傳送；若需預約傳送時，帶入格式為yyyyMMddhhmnss，例如:2009/01/01 13:00:00 則傳入20090101130000</param>
        /// <param name="PhoneNumbers">要傳送之電話號碼，多筆時以逗點(,)隔開。若為國際電話時，請用+86xxxxxxxx格式</param>
        /// <returns>true:傳送成功；false:傳送失敗</returns>
        public Boolean sendLongMessage(string Subject, string Content, string SendTime, string PhoneNumbers)
        {
            try
            {
               

                if (SendTime != "")
                {
                    if (SendTime.Length != 14)
                    {  //檢查傳送時間是否長度正確
                        return false;
                    }
                }

                string sendingXML = getSendingXML(PhoneNumbers, SendTime);

                string sResult = oMessage.QueueIn(m_sCustID, m_sCompanyNo, m_sUserNo, "110", "10", Subject, Content, "", "", sendingXML, "", "");


                if (sResult.Substring(0, 1) == "-")
                { // 發送失敗
                    return false;
                }

                string[] split = sResult.Split(',');
                m_iCredit = Convert.ToDouble(split[0]);

                return true;


            }
            catch(Exception er)
            {
                return false;
            }


        }
        public double getCredit(){
            return m_iCredit;
        }
        private string getSendingXML(string PhoneNumebers,string sendTime)
        {
            try{
                string xmlTemplate ="<REPS><IP/><CARD_NO/></REPS>";

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xmlTemplate);
               
                string[] phones=PhoneNumebers.Split(',');

                XmlNode node = doc.SelectSingleNode("/REPS");
                
                foreach(string s in phones){
                   
                    string mobile="";
                    if(s.Substring(0,2)=="09")  {   // 將09開頭之電話轉為 +8869開頭
                        mobile = "+8869" + s.Substring(2,8);
                    }else{
                        mobile = s;
                    }

                    XmlNode userNode = doc.CreateElement("USER");
                    node.AppendChild(userNode);

                                       
                    XmlAttribute nameAttribute = doc.CreateAttribute("NAME");
                    nameAttribute.Value = "";
                    userNode.Attributes.Append(nameAttribute);
                    
                    XmlAttribute mobileAttribute = doc.CreateAttribute("MOBILE");
                    mobileAttribute.Value =mobile;
                    userNode.Attributes.Append(mobileAttribute);

                    //Email
                    XmlAttribute emailAttribute = doc.CreateAttribute("EMAIL");
                    emailAttribute.Value = "";   
                    userNode.Attributes.Append(emailAttribute);

                    XmlAttribute paramAttribute = doc.CreateAttribute("PARAM");
                    paramAttribute.Value = "";
                    userNode.Attributes.Append(paramAttribute);

                    XmlAttribute sendtimeAttribute = doc.CreateAttribute("SENDTIME");
                    sendtimeAttribute.Value = sendTime.Trim();
                    userNode.Attributes.Append(sendtimeAttribute);


                }
                

                return doc.SelectSingleNode("/").InnerXml;

            }catch
            {
                return "";
            }

        }
    }
}
